package com.frejoys.common.filter;


import com.frejoys.common.wrapper.BodyReaderHttpServletRequestWrapper;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import java.io.IOException;

/**
 * 自定义过滤器，使用自定义body内容
 */
public class RepeatedlyReadFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {

            if (servletRequest.getContentType() != null && servletRequest.getContentType().contains("multipart/form-data")) {
                requestWrapper = new StandardServletMultipartResolver().resolveMultipart((HttpServletRequest) servletRequest);
            } else if (servletRequest.getContentType() != null && servletRequest.getContentType().contains("application/x-www-form-urlencoded")) {
                servletRequest.getParameterMap();
            }

            if (requestWrapper == null) {
                requestWrapper = servletRequest;
            }

            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) requestWrapper);
        }


        if (null != requestWrapper) {
            filterChain.doFilter(requestWrapper, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
